package com.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.util.ZookeeperClient;

/**
 * @description ZookeeperHttpSessionListener
 * @author TDW
 * @date 2018年6月8日
 *
 */
public class ZookeeperHttpSessionListener implements HttpSessionListener{

	
	private static final Logger logger = LoggerFactory.getLogger(ZookeeperHttpSessionListener.class);
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		sessionAction(+1);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		sessionAction(-1);
	}

	private void sessionAction(int a) {
		String thisServerNode =ZookeeperClient.SERVER_GROUP+ZookeeperClient.SERVER_PREFIX+ZookeeperClient.serverId;
		try {
			String serverInfoStr = new String(ZookeeperClient.client.getData(thisServerNode, false, null));
			int sessionSize = Integer.parseInt(serverInfoStr.split("#")[1])+a;
			ZookeeperClient.client.setData(thisServerNode, (serverInfoStr+"#"+sessionSize).getBytes(), -1);
		} catch (Exception e) {
			logger.error("设置session失败",e);
		}
	}

}
